package com.ambow.store.service.impl;

import com.ambow.store.service.UserService;
import com.ambow.store.service.exception.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ambow.store.entity.User;
import com.ambow.store.mapper.UserMapper;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

/**
* @author MyComputer
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2022-11-04 17:49:05
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public void addUser(User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(Strings.isNotEmpty(user.getUsername()),User::getUsername,user.getUsername());
        //获取username
        User result = this.getOne(userLambdaQueryWrapper);
        //判断用户名是否被占用
        if(result != null){
            throw new UserNameRepeatException("用户名重复，重新输入！");//被占用抛出异常
        }
        //将输入的密码进行加密
        String password = user.getPassword();
        //获取盐值（随机生成）
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将密码和盐值作为一个整体进行处理
        String md5Password = getMD5Password(password, salt);
        //将加密后的密码重新放入user对象中
        user.setPassword(md5Password);
        //将盐值放入
        user.setSalt(salt);

        //将数据写入数据库
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedUser(user.getUsername());
        user.setModifiedTime(date);
        boolean save = this.save(user);
        if(!save)
            throw new InsertException("注册时发生未知错误导致注册失败！");
    }

    @Override
    public User userLogin(User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(Strings.isNotEmpty(user.getUsername()),User::getUsername,user.getUsername());
        User result = this.getOne(userLambdaQueryWrapper);

        String md5Password = getMD5Password(user.getPassword(), result.getSalt());

        if (result.getUsername() == null){
            throw new UserNameNotFindExcetion("用户名不存在");
        }
        if (!result.getPassword().equals(md5Password)){
            throw new UserPasswordLoginExcetion("密码错误");
        }
        if (result.getIsDelete() == 1){
            throw new UserNameNotFindExcetion("用户名不存在");
        }
        User user1 = new User();
        user1.setUid(result.getUid());
        user1.setUsername(result.getUsername());
        user1.setAvatar(result.getAvatar());
        return user1;
    }

    @Override
    public void modifyUserPassword(User user, HttpSession session) {
        //获取session中的uid
        Object uid = session.getAttribute("uid");
        System.out.println(uid);
        //根据uid获取user对象
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUid,uid);
        //获取数据库中的User
        User userInDB = this.getOne(userLambdaQueryWrapper);
        //判断数据库中是否有数据或数据是否被禁用
        if (userInDB == null || userInDB.getIsDelete() == 1){
            throw new UserNameNotFindExcetion("用户名不存在");
        }
        //将前端传来的要修改的密码加密
        String md5Password = getMD5Password(user.getPassword(), userInDB.getSalt());
        //判断原密码与数据库密码是否一致
//        if (!userInDB.getPassword().equals(md5Password)){
//            throw new PasswordNotMatchException("密码错误");
//        }
        user.setUid((Integer) uid);
        user.setPassword(md5Password);
        user.setModifiedUser(userInDB.getUsername());
        Date date = new Date();
        user.setModifiedTime(date);
        this.updateById(user);

    }

    @Override
    public User getUserInfo(HttpSession session) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUid,session.getAttribute("uid"));
        User userData = this.getOne(userLambdaQueryWrapper);
        return userData;
    }

    @Override
    public void modifyUserInfo(User user,HttpSession session) {
        user.setUid((Integer) session.getAttribute("uid"));
        user.setModifiedUser((String) session.getAttribute("username"));
        user.setModifiedTime(new Date());
        this.updateById(user);
    }

    @Override
    public void modifyUserAvatar(User user) {
        user.setModifiedTime(new Date());
        boolean result = this.updateById(user);
        if (!result){
            throw new UpdateException("更新用户头像是发生未知错误");
        }
    }


    private String getMD5Password(String password,String salt){
        for (int i = 0 ; i < 3 ; i++){
            //MD5加密三次
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}




